package com.tm.fiverole.service.impl;

import com.tm.fiverole.entity.MenuEntity;
import com.tm.fiverole.mapper.MenuMapper;
import com.tm.fiverole.result.Result;
import com.tm.fiverole.result.ResultEnum;
import com.tm.fiverole.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangSang
 * @create 2022-08-18 21:12
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper mapper;
    @Override
    public Result queryMenuAll() {


     List<MenuEntity> menuEntityList= mapper.queryMenuAll();

        List<MenuEntity> tree = tree(menuEntityList, 0l);

        return Result.SUCCESS(tree);
    }

    @Override
    public Result postMenu(MenuEntity menuEntity) {

        mapper.addMenu(menuEntity);

        return Result.SUCCESS();
    }

    @Override
    public Result updateMenu(MenuEntity menuEntity) {

        List<MenuEntity> menuEntityList = menuEntity.getMenuEntityList();
        List<Long> list=new ArrayList<>();
        integers(menuEntityList,list);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i)==menuEntity.getPid()){
                return Result.ERROR(ResultEnum.ENUM_ERROR);
            }
        }
        return Result.SUCCESS();
    }

    @Override
    public Result deleteMenu(Integer id) {

    List<MenuEntity>   list =     mapper.queryIdMenu(id);

    if(list.size()>0 ){

        return Result.ERROR(ResultEnum.DEL_ERROR);
    }

        mapper.deleteMapper(id);

        return Result.SUCCESS();
    }


    private void integers(List<MenuEntity> menuEntityList,List<Long> list){

        for (int i = 0; i <menuEntityList.size() ; i++) {

            List<MenuEntity> menuEntityList1 = menuEntityList.get(i).getMenuEntityList();
            if(menuEntityList1.size()>0){
                integers(menuEntityList1,list);
            }
            list.add(menuEntityList.get(i).getId());
        }


    }


    private List<MenuEntity> tree( List<MenuEntity> menuEntityList , Long pid){

        List<MenuEntity> list = new ArrayList<>();
        for (int i = 0; i <menuEntityList.size() ; i++) {

            if(menuEntityList.get(i).getPid()==pid){
                long id = menuEntityList.get(i).getId();
                List<MenuEntity> tree = tree(menuEntityList, id);
                menuEntityList.get(i).setMenuEntityList(tree);
                list.add(menuEntityList.get(i));
            }


        }


        return list;
    }
}
